package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHUtil
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import sun.misc.BASE64Encoder

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.nio.charset.StandardCharsets
import java.text.SimpleDateFormat

/**
 *
 * @Title: apiSyncDemo
 * @Description:系统API接口开发Demo，重点关注业务逻辑部分
 * @author: LiJuntao
 * @date 2021-07-13 23:58:55
 *
 */

public class apiSyncDemo2 implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiSyncDemo2.class);
    private static final String CHARSET = "utf-8"; //设置字符集
    private static final Integer TIME_OUT = 100000; //设置请求超时时间
    private static final Integer ENABLE_SSL_FLAG = 0;

    static String URL;
    static String CALLBACKURL;
    static String APPKEY;
    static String APPID;

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

            try {
                //业务逻辑部分 测试

                URL = "https://qz.dbc61.com/api"; //获取法大大接口地址
                APPID = "100002";//获取法大大appid
                APPKEY = "E4uX9c65e5h7A5K5DA6rw6JL";//获取法大大接口签名key
                CALLBACKURL = "https://ronglian.dbc61.com/ngsapitask_ph/";//外部调用接口ip

                net.sf.json.JSONObject inJson = new net.sf.json.JSONObject();
                inJson.put("customerId", "2f43e2ea50db4275bc7b6bb6650e232c");
                inJson.put("mobile", "13925280099");
                net.sf.json.JSONObject fdd_AuthResJson = personAuth(inJson, "00005687", "202406270002", "09E7C113-B1CE-9336-8A83-6973F283FBE5", "2f43e2ea50db4275bc7b6bb6650e232c", "13925280099");
                log.debug("法大大系统推送认证返回结果:" + fdd_AuthResJson);
                return fdd_AuthResJson.toString();

            } catch (Exception e) {
                log.error("", e);

                return e.getMessage();
            }


    }

    /**
     * 法大大注册
     *
     * @param eliteBean 数据库操作工具
     * @param datajson  注册数据报文
     * @return
     */
    public static net.sf.json.JSONObject FDDCreateCust(EliteBean eliteBean, net.sf.json.JSONObject datajson) {
        net.sf.json.JSONObject result = new net.sf.json.JSONObject();
        //数据处理
        String customerid = datajson.getString("customerid");
        String customername = datajson.getString("customername");
        String customeroid = datajson.getString("customeroid");
        String customertypename = datajson.getString("customertypename");
        String idno = datajson.getString("idno");
        String mobile = datajson.getString("mobile");
        String sex = datajson.getString("sex");
        String iscompany = datajson.getString("iscompany");

        // String url = KHDBConfig.getAPIURL(eliteBean, "apiCustomerRegist");
        String url = "https://ronglian.dbc61.com/ngsapitask_ph/api/apiCustomerRegist";
        log.debug("接口地址:" + url);
        try {

            net.sf.json.JSONObject jsonBody = new net.sf.json.JSONObject();
            if (iscompany == "公司") {
                //如果是公司，先注册个人，再注册公司，传递个人为管理员
                net.sf.json.JSONObject jsonBody0 = new net.sf.json.JSONObject();
                jsonBody0.put("type", 1);
                jsonBody0.put("account", mobile);
                String commpanyResult = Util.doHttpPost(url, jsonBody0.toString(), CHARSET, TIME_OUT, ENABLE_SSL_FLAG);
                log.debug("如果是公司，先注册个人 返回:" + commpanyResult);

                net.sf.json.JSONObject fddobj0 = net.sf.json.JSONObject.fromObject(commpanyResult);
                String Fdd_customid = fddobj0.getString("data");
                log.debug("法大大个人认证ID返回:" + Fdd_customid);
                if (!KHUtil.isNull(Fdd_customid)) {
                    jsonBody.put("type", 2);
                    jsonBody.put("account", mobile);
                    jsonBody.put("companyName", customername);
                    jsonBody.put("adminAccountId", Fdd_customid);
                } else {
                    result.put("customer_guid", "");
                    result.put("customerid", "");
                    result.put("code", 400);
                    result.put("msg", "法大大企业注册失败！");
                    return result;
                }
            } else {
                jsonBody.put("type", 1);
                jsonBody.put("account", mobile);
            }
            log.debug("法大大注册参数:" + jsonBody.toString());

            String registerResult = Util.doHttpPost(url, jsonBody.toString(), CHARSET, TIME_OUT, ENABLE_SSL_FLAG);
            log.debug("法大大注册 结果String:" + registerResult);
            net.sf.json.JSONObject fddobj = net.sf.json.JSONObject.fromObject(registerResult);
            log.debug("法大大注册 结果JSONObject:" + fddobj);
            result.put("code", "200");
            result.put("msg", "法大大注册成功！");
            if (fddobj.getString("code") == "1" || fddobj.getString("code") == "1001003") {
                result.put("responseData", fddobj.getString("data"));
            }
            return result;
        } catch (Exception e) {
            log.error("调用注册异常信息:", e);
            result.put("customer_guid", "");
            result.put("customerid", "");
            result.put("code", 500);
            result.put("msg", "调用注册异常信息(" + e.getMessage() + ")");
            return result;
        }
    }


    /**
     * 个人认证
     *
     * @param inJson     接口报文
     * @param customerId 客户编号
     * @param batchId    批次号
     * @return
     */
    public static JSONObject personAuth(JSONObject inJson, String customerId, String batchId, String recGuid, String fddCustomerId, String mobile) throws Exception {
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");

        inJson.put("verifiedWay", 9);
        inJson.put("pageModify", 1);
        inJson.put("isSendSms", 1);
        inJson.put("isRepeatVerified", 1);
        inJson.put("notifyUrl", CALLBACKURL + "/api/apiBatchSignContract?batchId=" + batchId + "&callbackType=认证回调&customerId=" + customerId + "&recGuid=" + recGuid);
        log.debug("请求报文加密前：" + inJson.toString());

        String bizContent = getbizContent(inJson.toString());
        bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", "");

        JSONObject jsons = new JSONObject();
        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        jsons.put("timestamp", datetime);
        jsons.put("bizContent", bizContent);
        jsons.put("signType", "SHA256");
        jsons.put("appId", APPID);
        String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
        log.debug("请求报文签名前：" + signString);

        String signstr1 = Util.getSHA256Str(signString).toUpperCase();
        log.debug("请求报文签名signstr1：" + signstr1);

        String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
        log.debug("请求报文签名signstr2：" + signstr2);

        String sign = new BASE64Encoder().encode(signstr2.getBytes(StandardCharsets.UTF_8));
        log.debug("请求报文签名后：" + sign);
        jsons.put("sign", sign);
        log.debug("用户个人认证请求Body参数:" + jsons);

        String Assemblys = Util.doHttpPostUseHead(URL + "/certification/person/url", jsons.toString().replace("\\n", ""), CHARSET, TIME_OUT, ENABLE_SSL_FLAG, headMap);
        log.debug("个人认证请求返回报文：" + Assemblys);

        JSONObject obj = JSONObject.fromObject(Assemblys);

        if (obj.getString("code") == "1002021" || (obj.getString("code") == "1002020" && obj.getString("msg").contains("该用户已实名认证通过，不能设置允许修改页面"))) {
            JSONObject inJsonTwo = new JSONObject();
            inJsonTwo.put("customerId", fddCustomerId);
            inJsonTwo.put("mobile", mobile);
            inJsonTwo.put("verifiedWay", 9);
            inJsonTwo.put("pageModify", 1);
            inJsonTwo.put("isSendSms", 1);
            inJsonTwo.put("isRepeatVerified", 2);
            inJsonTwo.put("notifyUrl", CALLBACKURL + "/api/apiBatchSignContract?batchId=" + batchId + "&callbackType=认证回调&customerId=" + customerId + "&recGuid=" + recGuid);
            log.debug("参数不一致不允许继续认证,重新认证请求报文加密前：" + inJsonTwo.toString());
            String bizContents = getbizContent(inJsonTwo.toString());
            bizContents = bizContents.replaceAll("\\n", "").replaceAll("\\r", "");
            ;
            JSONObject jsonsZ = new JSONObject();
            String datetimes = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            jsonsZ.put("timestamp", datetimes);
            jsonsZ.put("bizContent", bizContents);
            jsonsZ.put("signType", "SHA256");
            jsonsZ.put("appId", APPID);
            String signStrings = "appId=" + APPID + "&bizContent=" + bizContents + "&signType=SHA256&timestamp=" + datetimes;
            signStrings = signStrings.replace("\\n", "");

            String signstr1s = Util.getSHA256Str(signStrings).toUpperCase();
            String signstr2s = Util.getSHA256Str(signstr1s + APPKEY).toUpperCase();
            String signs = new BASE64Encoder().encodeBuffer(signstr2s.getBytes("UTF-8"));
            jsonsZ.put("sign", signs);

            log.debug("参数不一致不允许继续认证,重新认证用户个人认证参数:" + jsonsZ.toString().replace("\\n", ""));
            String AssemblysZ = Util.doHttpPostUseHead(URL + "/certification/person/url", jsonsZ.toString().replace("\\n", ""), CHARSET, TIME_OUT, ENABLE_SSL_FLAG, headMap);
            log.debug("个人认证重新请求返回报文：" + AssemblysZ);
            obj = JSONObject.fromObject(AssemblysZ);
        }
        return obj;
    }


    // 获取bizContent
    public static String getbizContent(String param) throws Exception {
        log.debug("加密的业务参数bizContent:" + param);
        String encodedObject = URLEncoder.encode(param, "UTF-8");
        log.debug("加密的业务参数bizContent URLEncoder:" + encodedObject);
        String biz_contents = new BASE64Encoder().encodeBuffer(encodedObject.getBytes("UTF-8"));
        log.info("加密的业务参数bizContent[bizContent]:" + biz_contents);

        return biz_contents;
    }
}